//
//  HMComposeView.swift
//  Weibo
//
//  Created by Apple on 2017/7/16.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import pop

//  自定义撰写视图
class HMComposeView: UIView {
    var target: UIViewController?
    
    //  记录撰写菜单按钮
    private lazy var composeButtonArray: [HMComposeButton] = [HMComposeButton]()
    //  撰写菜单模型数组
    private lazy var composeArray: [HMCompose] = {
        let array = self.loadComposeData()
        return array
    }()
    //  MARK:   --懒加载控件
    private lazy var bgImageView: UIImageView = {
        //  获取模糊图片
        let image = self.getScreenShot().applyLightEffect()
        let imageView = UIImageView(image: image)
        return imageView
    }()
    //  标语
    private lazy var sloganImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        addSubview(bgImageView)
        addSubview(sloganImageView)
        sloganImageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(100)
        }
        addChildButton()
        
    }
    
    //  添加撰写菜单按钮
    private func addChildButton() {
        
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 110
        let buttonMargin: CGFloat = (width - 3 * buttonWidth) / 4
        
        
        for i in 0..<6 {
            
            let colIndex = i % 3
            let rowIndex = i / 3
            
            let button = HMComposeButton()
            button.tag = i
            button.addTarget(self, action: #selector(buttonAction(btn:)), for: .touchUpInside)
            button.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            button.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonMargin + ScreenHeight
            let compose = composeArray[i]
            button.setImage(UIImage(named: compose.icon!), for: .normal)
            button.setTitle(compose.title, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.setTitleColor(UIColor.gray, for: .normal)
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            addSubview(button)
            composeButtonArray.append(button)
        }
        
        
    }
    
    //  开启pop动画
    private func startPopAnimation(isUp: Bool) {
        
        if isUp == false {
            composeButtonArray = composeButtonArray.reversed()
        }
        
        for (i, button) in composeButtonArray.enumerated() {
            let popAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            if isUp {
                popAnimation?.toValue = CGPoint(x: button.centerX, y: button.centerY - 350)
            } else {
                popAnimation?.toValue = CGPoint(x: button.centerX, y: button.centerY + 350)
            }
            
            popAnimation?.springSpeed = 10
            popAnimation?.springBounciness = 10
            popAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            //  执行pop动画
            button.pop_add(popAnimation, forKey: nil)
        }
        
    }
    
    
    //  截取屏幕图片
    private func getScreenShot() -> UIImage {
        let window = UIApplication.shared.keyWindow!
        //  开启图片上下文
        UIGraphicsBeginImageContext(window.size)
        //  截取window到指定区域内
        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.size), afterScreenUpdates: false)
        //  获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //  结束图片上下文
        UIGraphicsEndImageContext()
        return image!
    }
    
    
    //  MARK:   --撰写菜单按钮点击事件
    @objc private func buttonAction(btn: HMComposeButton) {
        UIView.animate(withDuration: 0.25, animations: { 
            for button in self.composeButtonArray {
                button.alpha = 0.3
                if button == btn {
                    //  发大
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                } else {
                    //  缩小
                    button.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
                }
            }
        }) { (_) in
         
            UIView.animate(withDuration: 0.25, animations: { 
                for button in self.composeButtonArray {
                    button.transform = CGAffineTransform.identity
                    button.alpha = 1
                }
            }, completion: { (_) in
                //  弹出控制器
                let compose = self.composeArray[btn.tag]
                //  1.自定义类型需要加上命名空间，获取字符串对应的class
                let classType = NSClassFromString(compose.className!) as! UIViewController.Type
                //  2.必须要指定对应的class 类型, 调用init构造函数
                let vc = classType.init()
                let nav = HMNavigationController(rootViewController: vc)
                self.target?.present(nav, animated: true, completion: {
                    self.removeFromSuperview()
                })
                
            })
            
        }
    }
    
    //  读取compose.plist数据
    private func loadComposeData() -> [HMCompose] {
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let composeDicArray = NSArray(contentsOfFile: path) as! [[String: Any]]
        //  字典转模型
        let composeArray = NSArray.yy_modelArray(with: HMCompose.self, json: composeDicArray) as! [HMCompose]
        return composeArray
    }
    
    //  显示罩层
    func show(target: UIViewController) {
        self.target = target
        target.view.addSubview(self)
        startPopAnimation(isUp: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        startPopAnimation(isUp: false)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { 
            self.removeFromSuperview()
        }
    }

}
